<template>
  <div class="contractAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave() "
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 账期结算收款 -->
      <el-collapse-item
        name="1"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">账期结算收款</span>
        </template>
        <div class="contract-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="100px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="回款项目：" prop="projectId">
                  <el-select
                    ref="refSelect"
                    style="width: 268px; heigth: 100%"
                    v-model="contactForm.projectId"
                    placeholder="请选择"
                    clearable
                    value-key="projectId"
                    @change="handleProjectChange"
                  >
                    <el-option
                      v-for="(item, index) in projectList"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item.projectId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="实收账期：" prop="actualAccountPeriod">
                  <el-select
                    v-model="contactForm.actualAccountPeriod"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleMoneyChange"
                  >
                    <el-option
                      v-for="dict in paymentDaysList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="实收日期："
                  label-width="150"
                  prop="actualDate"
                >
                  <el-date-picker
                    v-model="contactForm.actualDate"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="实收金额："
                  label-width="120"
                  prop="actualMoney"
                >
                  <el-input
                    v-model="contactForm.actualMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="21"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="是否开票：" prop="isInvoiced">
                  <el-select
                    v-model="contactForm.isInvoiced"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleInvoiceChange"
                  >
                    <el-option
                      v-for="dict in flagList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="开票金额："
                  :prop="contactForm.isInvoiced == 1 ? '' : 'invoiceMoney'"
                  ref="isInvoicedformitem"
                >
                  <el-input
                    v-model="contactForm.invoiceMoney"
                    placeholder="请输入"
                    clearable
                    maxlength="21"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="开票日期："
                  label-width="150"
                  :prop="contactForm.isInvoiced == 1 ? '' : 'invoiceDate'"
                  ref="invoiceDateformitem"
                >
                  <el-date-picker
                    v-model="contactForm.invoiceDate"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="备注：">
                  <el-input
                    style="width: 96%"
                    v-model="contactForm.remark"
                    placeholder="请输入"
                    clearable
                    maxlength="2000"
                    class="search-input"
                    @keyup.enter.stop="handleContactAdd(contactFormRef)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 实收账期信息 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">实收账期信息</span>
          <div
            class="nofixed-search-button button-position"
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.contractActualInfoRespVos"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="回款项目"
              prop="projectName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收账期"
              prop="actualAccountPeriodName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收日期"
              prop="actualDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="实收金额"
              prop="actualMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="是否开票"
              prop="isInvoicedName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="开票金额"
              prop="invoiceMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="开票日期"
              prop="invoiceDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
      <!-- 计划账期信息 -->
      <el-collapse-item
        name="3"
        style="position: relative; margin-top: 20px"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">计划账期信息</span>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.contractPlanInfoRespVos"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column
              label="项目名称"
              prop="projectName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="计划账期"
              prop="planAccountPeriodName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="应收日期"
              prop="receivableDate"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="应收金额"
              prop="receivableMoney"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { getUserListApi } from "@/api/information/customer";
import {
  addContractMoney,
  getProjectListApiSec,
  getContractDetailApi,
} from "@/api/sales/contract";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 回款新增组件显隐
  "contractAddShow",
  // 更新回款组件显隐
  "update:contractAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
//  详情加载效果
const detailInfoShow = ref(false);
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 下拉框引用
const refSelect = ref();
// 合同表单模板
const contractFormTemplate = {
  contractActualInfoRespVos: [],
  contractPlanInfoRespVos: [], // 账期结算计划收款明细对象
};
const data = reactive({
  //合同表单
  contractForm: JSON.parse(JSON.stringify(contractFormTemplate)),
  // 联系人表单
  contactForm: {
    actualAccountPeriod: null, // 计划账期
    actualAccountPeriodName: "", // 计划账期中文
    actualDate: "", // 实收日期
    actualMoney: null, // 	实收金额
    actualMoneyId: null, //实收金额
    contractId: null, // 关联的合同id
    invoiceDate: "", // 开票日期
    invoiceMoney: null, // 开票金额
    isInvoiced: null, // 是否开票
    isInvoicedName: "", // 是否开票中文
    projectId: null, // 	关联项目id
    projectName: "", // 	关联项目中文
    remark: "", // 备注
  },
  // 校验规则
  queryContactRules: {
    actualMoney: [
      { required: true, message: "请输入实收金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    invoiceMoney: [
      { required: true, message: "请输入开票金额", trigger: "blur" },
      {
        pattern: /^\d{1,20}(\.\d+)?$/,
        message: "只能输入最多20位数字",
        trigger: "blur",
      },
    ],
    projectId: [
      { required: true, message: "请选择回款项目", trigger: "change" },
    ],
    actualAccountPeriod: [
      { required: true, message: "请选择实收账期", trigger: "change" },
    ],
    actualDate: [
      { required: true, message: "请选择实收日期", trigger: "change" },
    ],
    isInvoiced: [
      { required: true, message: "请选择是否开票", trigger: "change" },
    ],
    invoiceDate: [
      { required: true, message: "请选择开票日期", trigger: "change" },
    ],
  },
  // 账期列表
  paymentDaysList: [],
  // 用户列表
  userList: [],
  // 项目列表
  projectList: [],
  // 是否列表
  flagList: [
    {
      label: "是",
      value: 0,
    },
    {
      label: "否",
      value: 1,
    },
  ],
});
const {
  contractForm,
  contactForm,
  queryContactRules,
  paymentDaysList,
  userList,
  projectList,
  flagList,
} = toRefs(data);
const contactAddShow = ref(false);

/**
 * @description: 保存
 */
const handleAddSave = async () => {
  ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const res = await addContractMoney(contractForm.value);
      if (res.code === 200) {
        emit("update:contractAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:contractAddShow", false);
    contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:contractAddShow", false);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (operateType.value === "edit") {
        contractForm.value.contractActualInfoRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        contractForm.value.contractActualInfoRespVos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = {
        contactRoleName: "",
        birthday: "",
        address: "",
        contactId: null,
        phone: "",
        name: "",
        wechat: "",
        contractId: null,
        contactRole: null,
        position: "",
        remarks: "",
        hobby: "",
      };
      contactFormRef.resetFields();
      nextTick(() => {
        refSelect.value.focus();
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理项目选择
 * @param {Number} value 当前值
 */
const handleProjectChange = async (value) => {
  contactForm.value.projectName =
    projectList.value.find((item) => item.projectId === value)?.projectName ||
    "";
};

/**
 * @description: 处理实际回款选择
 * @param {Number} value 当前值
 */
const handleMoneyChange = async (value) => {
  contactForm.value.actualAccountPeriodName =
    paymentDaysList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理是否开票
 * @param {Number} value 当前值
 */
let isInvoicedformitem = ref(null);
let invoiceDateformitem = ref(null);
const handleInvoiceChange = async (value) => {
  isInvoicedformitem.value.clearValidate();
  invoiceDateformitem.value.clearValidate();
  contactForm.value.isInvoicedName =
    flagList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理销售清单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refSelect.value.focus();
    });
  } else {
    contractForm.value.contractActualInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getContractDetailApi(id);
    contractForm.value = {
      ...res.data.contractInfoRespVo,
      contractPlanInfoRespVos: res.data.contractPlanInfoRespVos,
      contractAccessory: res.data.contractAccessory,
      contractActualInfoRespVos: res.data.contractActualInfoRespVos,
    };
    await getProjectListApiSec(id).then((res) => {
      if (res) {
        projectList.value = res;
      }
    });
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_account_period").then((res) => {
    if (res.code === 200) {
      paymentDaysList.value = res.data;
    }
  });
  await getUserListApi().then((res) => {
    if (res.code === 200) {
      userList.value = res.rows;
    }
  });
}

onMounted(() => {
  getDicts();
  nextTick(() => {
    refSelect.value.focus();
  });
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.contractAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .contract-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }
  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
}
</style>
